package org.example.data;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.google.common.collect.Lists;
import lombok.Data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 下载社区数据
 * 通过Kimi生成的代码，需要根据自己的需求进行调整
 */

public class CommunityDataFetcher {

    private static final String BASE_URL = "https://hubei.tianditu.gov.cn/mapApi/v2/search";
    private static final String TK = "9a73ad6c81a15dbc1a4aec0a9cf8f7f1";
    private static final int TOTAL_PAGES = 283;
//    private static final int TOTAL_PAGES = 1;
    private static final int COUNT_PER_PAGE = 10;
    private static final String SPECIFY = "156420500";
    private static final String KEY_WORD = "社区";

    public static void main(String[] args) {
        List<Community> communities = new ArrayList<>();
        for (int start = 0; start <= TOTAL_PAGES * COUNT_PER_PAGE; start += COUNT_PER_PAGE) {
            try {
                String response = sendGetRequest(BASE_URL, buildQuery(start));
                communities.addAll(parseResponse(response));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 打印或处理采集到的社区信息
//        for (Community community : communities) {
//            System.out.println(community);
//        }
        FileUtil.writeString(JSONUtil.toJsonStr(communities), "d:\\社区信息.json", StandardCharsets.UTF_8);
        exportExcel(communities);
    }

    private static void exportExcel(List<Community> list){
        // 创建ExcelWriter对象
        ExcelWriter writer = new ExcelWriter("d:\\社区信息.xlsx");

        // 设置样式
        StyleSet style = writer.getStyleSet();
        // 设置列宽
        style.setWrapText();
        // 设置表头样式
        style.setFont((short)0, (short)10, "宋体", false);

        // 写入表头
        List<String> hearderRow = Lists.newArrayList("地址", "电话", "类型", "名称", "来源", "热力ID", "经纬度", "经度", "纬度");
        writer.writeHeadRow(hearderRow);

        // 写入数据
        writer.write(list, true);

        // 关闭writer，释放内存
        writer.close();
    }
    private static String buildQuery(int start) {
        System.out.println("start: "+start);
        return "?postStr=%7B%22yingjiType%22:0,%22sourceType%22:0,%22mapBound%22:%22110.08848133853897,29.940859984342577,112.24358899746116,31.565027483657563%22,%22level%22:%229%22,%22dataTypes%22:%22%22,%22queryType%22:1,%22count%22:10,%22specify%22:" + SPECIFY + ",%22queryTerminal%22:10000,%22keyWord%22:%22%E7%A4%BE%E5%8C%BA%22,%22start%22:" + start + "%7D&type=query&tk=" + TK;
//        String params = "{\"yingjiType\":0,\"sourceType\":0,\"mapBound\":\"110.08848133853897,29.940859984342577,112.24358899746116,31.565027483657563\",\"level\":\"9\",\"dataTypes\":\"\",\"queryType\":1,\"count\":10,\"specify\":\" + SPECIFY + \",\"queryTerminal\":10000,\"keyWord\":"+KEY_WORD+",\"start\":\" + start + \"}";
//        return "?postStr="+URLEncoder.encode(params, StandardCharsets.UTF_8)+"&type=query&tk=" + TK;
    }

    private static String sendGetRequest(String urlString, String query) throws IOException {
        URL url = new URL(urlString + query);
//        System.out.println(url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        // 设置请求头
        Map<String, String> requestHeaders = new HashMap<>();
        requestHeaders.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
        requestHeaders.put("Accept", "application/json");
        requestHeaders.put("Accept-Language", "en-US,en;q=0.5");
        requestHeaders.put("Connection", "keep-alive");
        requestHeaders.put("Cache-Control", "max-age=0");

        for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
            conn.setRequestProperty(header.getKey(), header.getValue());
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }

        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            return response.toString();
        }
    }

    private static List<Community> parseResponse(String json) {
        RespJSon respJSon = JSONUtil.toBean(json, RespJSon.class);
        if(Long.parseLong(respJSon.getCount())==0){
            System.out.println(json);
            throw new RuntimeException("数据返回异常，没有数据~~！");
        }
        if(CollectionUtil.isNotEmpty(respJSon.getPois())){
//            return BeanUtil.copyToList(respJSon.getPois(), Community.class);
            return respJSon.getPois().stream().peek(item->{
                if(StrUtil.isNotBlank(item.getLonlat())){
                    String[] split = item.getLonlat().split(",");
                    item.setLon(Double.parseDouble(split[0].trim()));
                    item.setLat(Double.parseDouble(split[1].trim()));
                }
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

}
